export const field = (http, dialog, api, ConfigApiService) => {
	var dataTypes = [{
			name: '字符串',
			value: 'STRING'
		}, {
			name: '文本型',
			value: 'TEXT'
		}, {
			name: '整型',
			value: 'INT'
		}, {
			name: '长整型',
			value: 'LONG'
		}, {
			name: '时间型',
			value: 'DATATIME'
		}],
		formTypes = [{
			name: '普通文本',
			value: 'SingleTextBox'
		}, {
			name: '多行文本',
			value: 'MultiTextBox'
		}, {
			name: '文本编辑器',
			value: 'RichTextBox'
		}, {
			name: '下拉框',
			value: 'DropDownList'
		}, {
			name: '单选框',
			value: 'RadioButtonList'
		}, {
			name: '多选框',
			value: 'CheckBoxList'
		}, {
			name: '日期选择框',
			value: 'DateTime'
		}, {
			name: '图片上传',
			value: 'UpImage'
		}, {
			name: '附件上传',
			value: 'UpFile'
		}];

	var styleName = 'styles',
		// 设置表单默认初始值
		_defaults = {
			formType: formTypes[0].value,
			required: 1,
			display: 1,
			readOnly: 0,
			exhibition : 0,
			optionType: 1,
			options: [],
			rules: [],
			search: 0
		};

	function applyDefault(data, defaults) {
		for (var p in defaults) {
			if (data[p] == null) {
				data[p] = defaults[p];
			}
		}
		return data;
	}

    function selectOptions() {
        var loadOptionsData = function(scope, params) {
            params = params || {};
            angular.extend(params, {
                type: 1
            });
            return api.gridLoad({
                name: 'dictionary',
                params: params,
                scope: scope || this,
                success: function(data, options) {
                    var _scope = this;
                    _scope.fields = angular.merge({}, _scope.fields, data.fields);
                }
            });
        };
        return api.form({
            title: '选择字典数据',
            template: require('../views/form_options.tpl.html'),
            name: 'meta_options_filter',
            beforeSubmit: function(data, deferred) {
                var id = api.getGridSelectedId(this);
                if (!id) {
                    dialog.alert('请选取需要导入的数据！');
                    return false;
                }
                data.id = id;
            },
            scope: {
                q: {},
                fields: {
                    types: [{
                        id: 1,
                        name: '系统级'
                    }, {
                        id: 2,
                        name: '用户级'
                    }]
                },
                query: function(resetPage) {
                    var scope = this;
                    if (resetPage === false || scope.gridOptions.paginationCurrentPage == 1) {
                        loadOptionsData(scope, scope.q);
                    } else {
                        api.gridReset(null, scope);
                    }
                },
                gridOptions: {
                    paginationCurrentPage: api.page.pageNumber,
                    paginationPageSize: api.page.pageSize,
                    useExternalPagination: true,
                    multiSelect: false,
                    columns: [{
                        name: '序号',
                        width: 50,
                        cellTemplate: '<div class="x-grid-inner">{{(grid.options.paginationCurrentPage - 1) * grid.options.paginationPageSize + (index + 1)}}</div>'
                    }, {
                        name: '字段名称',
                        width: 200,
                        field: 'field'
                    }, {
                        name: '显示名称',
                        width: 200,
                        field: 'fieldName'
                    }, {
                        name: '类型',
                        width: 150,
                        field: 'type',
                        cellTemplate: '<div class="x-grid-inner" ng-bind-html="grid.appScope.mapping(grid, row, col, \'types\')"></div>'
                    }, {
                        name: '操作',
                        width: 100,
                        field: 'id',
                        cellTemplate: '<div class="x-grid-inner"><span class="btn-text" ng-click="grid.appScope.preview(grid.getCellValue(row, col))">详情</span></div>'
                    }],
                    forceFit: false,
                    onRegisterApi: function(api, grid) {
                        var scope = grid.appScope;
                        scope.api = api;

                        api.pagination && api.pagination.on.paginationChanged(scope, function(newPage, pageSize) {
                            scope.query(false);
                        });
                    }
                },
                mapping: function(grid, row, col, field) {
                    return api.mapping({
                        grid: grid,
                        row: row,
                        col: col,
                        field: field,
                        scope: this
                    });
                },
                preview: function(id) {
                    api.form({
                        title: '字典详情',
                        template: require('../../dictionary/views/form_preview.tpl.html'),
                        resolveWait: http.post({
                            name: 'dictionary_preview',
                            params: {
                                id: id
                            }
                        })
                    })
                },
                hasSelectedRecords: function(apiName) {
                    return api.hasGridSelectedRecords(this, apiName);
                }
            },
            resolveApply: false,
            resolveWait: function() {
                var _scope = this;
                return loadOptionsData(_scope);
            },
            config: {
                width: 720
            }
        });
    }

	function addStyle() {
		var _scope = this;
		_scope.data[_scope.styleName] = _scope.data[_scope.styleName] || [];

		var _data = applyDefault({
				mid: _scope.data.id
			}, _defaults);
		api.form({
			title: '新建样式', 
			template: require('../views/form_field_style.tpl.html'),
			data: _data,
			name: 'meta_field_style_add',
            beforeSettings: function() {
                ConfigApiService.reset().addJson();
            },
			beforeSubmit: function(data) {
                data.options = ConfigApiService.getResultArray();
                data.optionResult = null;
				if (!_scope.data.id) {
					_scope.data[_scope.styleName].push(data);
					this.close();
					return false;
				}
			},
			scope: {
				formTypes: formTypes,
                addJson: ConfigApiService.addJson,
                jsonArray: ConfigApiService.jsonArray,
                getKey: ConfigApiService.getKey,
                removeJson: ConfigApiService.removeJson,
                movePrev: ConfigApiService.movePrev,
                moveNext: ConfigApiService.moveNext,
                selectOptions: function() {
                    var _scope = this,
                        _data = _scope.data;
                    selectOptions().then(function(data) {
                    	_data.dicId = data.id;
                        _data.optionResult = data;
                    });
                },
                preview: function(id) {
                    api.form({
                        title: '字典详情',
                        template: require('../../dictionary/views/form_preview.tpl.html'),
                        resolveWait: http.post({
                            name: 'dictionary_preview',
                            params: {
                                id: id
                            }
                        })
                    })
                }
			},
			config: {
				size: 640
			}
		}).then(function(r) {
			r && _scope.data[_scope.styleName].push(r);
		});
	}
	function editStyle(index, style) {
		var _scope = this;

		api.form({
			title: '编辑样式',
			template: require('../views/form_field_style.tpl.html'),
			name: 'meta_field_style_edit',
            beforeSettings: function() {
                ConfigApiService.reset();
            },
			beforeSubmit: function(data) {
                data.options = ConfigApiService.getResultArray();
                data.optionResult = null;
				if (!style.id) {
					_scope.data[_scope.styleName][index] = data;
					this.close();
					return false;
				}
			},
			scope: {
				formTypes: formTypes,
                addJson: ConfigApiService.addJson,
                jsonArray: ConfigApiService.jsonArray,
                getKey: ConfigApiService.getKey,
                removeJson: ConfigApiService.removeJson,
                movePrev: ConfigApiService.movePrev,
                moveNext: ConfigApiService.moveNext,
                selectOptions: function() {
                    var _scope = this,
                        _data = _scope.data;
                    selectOptions().then(function(data) {
                    	_data.dicId = data.id;
                        _data.optionResult = data;
                    });
                },
                preview: function(id) {
                    api.form({
                        title: '字典详情',
                        template: require('../../dictionary/views/form_preview.tpl.html'),
                        resolveWait: http.post({
                            name: 'dictionary_preview',
                            params: {
                                id: id
                            }
                        })
                    })
                }
			},
			resolveWait: {
				style: function() {
					var _data = _scope.data[_scope.styleName][index];
					return style.id ? http.post({
						name: 'meta_field_style',
						params: {
							id: style.id
						}
					}) : applyDefault(_data, _defaults);
				}
			},
			resolveApplyData: ['style'],
            resolveAfter: function(data) {
                var _scope = this;
                ConfigApiService.setArrayData(data.options);
            },
			config: {
				size: 640
			}
		}).then(function(r) {
			r && angular.extend(style, r);
		});
	}
	function removeStyle(index, style) {
		var _scope = this;
		dialog.confirm('确定要移除当前样式？').result.then(function(r) {
			if (r) {
				var _styles = _scope.data[_scope.styleName];
				if (_styles.length) {
					if (style.id) {
						_scope.removing = true;
						http.post({
							name: 'meta_field_style_remove',
							params: {
								id: style.id
							},
							success: function() {
								_styles.splice(index, 1);
							}
						})['finally'](function() {
							_scope.removing = false;
						})
					} else {
						_styles.splice(index, 1);
					}
				}
			}
		});
	}

	var service = {
		dataTypes: dataTypes,
		formTypes: formTypes,
		add: function(params) {
			var data = {
					dataType: dataTypes[0].value
				};
			angular.extend(data, params);
			return api.form({
				title: '新建指标',
				template: require('../views/form_field.tpl.html'),
				name: 'meta_field_add',
				data: data,
				scope: {
					styleName: styleName,
					dataTypes: dataTypes,
					getFormTypeName: service.getFormTypeName,
					addStyle: addStyle,
					editStyle: editStyle,
					removeStyle: removeStyle
				},
				beforeSubmit: function(data) {
					if (!data[styleName] || data[styleName].length ===0) {
						dialog.alert('请至少添加一个样式');
						return false;
					}
				}
			});
		},
		edit: function(id) {
			return api.form({
				title: '编辑指标',
				template: require('../views/form_field.tpl.html'),
				// name: 'meta_field_edit',
				data: {
					dataType: dataTypes[0].value
				},
				scope: {
					styleName: styleName,
					state: {
						editModel: true,
						editable: false
					},
					dataTypes: dataTypes,
					getDataTypeName: service.getDataTypeName,
					getFormTypeName: service.getFormTypeName,
					addStyle: addStyle,
					editStyle: editStyle,
					removeStyle: removeStyle,
					edit: function() {
						this.state.editable = !this.state.editable;
					},
					save: function() {
						var _scope = this;
						var _data = _scope.data;
						http.post({
							name: 'meta_field_save',
							params: {
								id: id,
								metricCode: _data.metricCode,
								metricName: _data.metricName,
								fieldType: _data.fieldType,
								fieldLength: _data.fieldLength,
								metricDes: _data.metricDes,
								metricCn: _data.metricCn
							},
							success: function(data) {
								dialog.notify('字段属性修改成功！');
								_scope.state.editable = false;
							}
						});
					},
					cancel: function() {
						this.state.editable = !this.state.editable;
					}
				},
				resolveWait: http.post('meta_field_styles', {
					id: id
				})
			});
		},
		getTypeName: function(types, value) {
			var name;
			types = types || [];
			types.forEach(function(type) {
				type = type || {};
				if (type.value == value) {
					name = type.name;
					return;
				}
			});
			return name;
		},
		getFormTypeName: function(value) {
			return service.getTypeName(service.formTypes, value);
		},
		getDataTypeName: function(value) {
			return service.getTypeName(service.dataTypes, value);
		}
	}
	return service;
}
field.$inject = ['ui.http', 'ui.dialog', 'ui.api', 'ConfigApiService'];